import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///计算贷款Widget
class LoanCalculatePage extends StatefulWidget {
  const LoanCalculatePage({super.key});

  @override
  State<LoanCalculatePage> createState() => _LoanCalculatePageState();
}

class _LoanCalculatePageState extends State<LoanCalculatePage> {
  final MaterialStatesController _materialStatesController = MaterialStatesController({MaterialState.disabled});
  final TextEditingController _loanAmountController = TextEditingController();
  final TextEditingController _loanTermController = TextEditingController();
  final TextEditingController _loanRateController = TextEditingController();

  double? paymentPerMonth = 0.0;

  @override
  void initState() {
    super.initState();
    _loanAmountController.addListener(() {
      _materialStatesController.update(MaterialState.disabled, !_checkAllFieldHasInput());
    });
    _loanTermController.addListener(() {
      _materialStatesController.update(MaterialState.disabled, !_checkAllFieldHasInput());
    });
    _loanRateController.addListener(() {
      _materialStatesController.update(MaterialState.disabled, !_checkAllFieldHasInput());
    });
  }

  bool _checkAllFieldHasInput() {
    return _loanAmountController.text.isNotEmpty &&
        _loanTermController.text.isNotEmpty &&
        _loanRateController.text.isNotEmpty;
  }

  _computePayment() {
    if (_checkAllFieldHasInput()) {
      double loanAmount = double.parse(_loanAmountController.text);
      int loanTerm = int.parse(_loanTermController.text);
      double loanRate = double.parse(_loanRateController.text) / 100 / 12;
      double monthlyPayment =
          loanAmount * loanRate * pow((1 + loanRate), loanTerm) / (pow((1 + loanRate), loanTerm) - 1);
      setState(() {
        paymentPerMonth = monthlyPayment;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('贷款试算'),
      ),
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              InputUnit(
                placeholder: '贷款金额',
                unit: '元',
                controller: _loanAmountController,
              ),
              const Padding(padding: EdgeInsets.only(bottom: 16.0)),
              InputUnit(
                placeholder: '贷款期数',
                unit: '月',
                decimal: false,
                controller: _loanTermController,
              ),
              const Padding(padding: EdgeInsets.only(bottom: 16.0)),
              InputUnit(
                placeholder: '贷款利率',
                unit: '%',
                controller: _loanRateController,
              ),
              const Padding(padding: EdgeInsets.only(bottom: 50.0)),
              TextButton(
                onPressed: _computePayment,
                statesController: _materialStatesController,
                style: ButtonStyle(
                    backgroundColor: MaterialStateProperty.resolveWith((states) {
                      if (states.contains(MaterialState.disabled)) {
                        return Colors.grey;
                      } else {
                        return const Color(0xff6076ff);
                      }
                    }),
                    minimumSize: const MaterialStatePropertyAll(Size(double.infinity, 50))),
                child: const Text('开始计算'),
              ),
              Padding(
                padding: const EdgeInsets.only(top: 20.0),
                child: Offstage(
                  offstage: paymentPerMonth == 0,
                  child: Text('月还款:$paymentPerMonth元'),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _materialStatesController.dispose();
    _loanAmountController.dispose();
    _loanTermController.dispose();
    _loanRateController.dispose();
  }
}

class InputUnit extends StatefulWidget {
  final String unit;
  final String placeholder;
  final bool? decimal;
  final TextEditingController? controller;

  const InputUnit({super.key, required this.unit, required this.placeholder, this.controller, this.decimal});

  @override
  State<InputUnit> createState() => _InputUnitState();
}

class _InputUnitState extends State<InputUnit> {
  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
          child: CupertinoTextField(
            controller: widget.controller,
            placeholder: widget.placeholder,
            keyboardType: TextInputType.numberWithOptions(decimal: widget.decimal ?? true),
          ),
        ),
        SizedBox(
          width: 50,
          child: Center(child: Text(widget.unit)),
        ),
      ],
    );
  }
}
